package com.hnluchuan.staff.web.controller.admin;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileInputStream;

import com.hnluchuan.staff.dto.EmployeeDTO;
import com.hnluchuan.staff.service.StudentService;
import com.hnluchuan.utils.exception.BizException;
import org.apache.commons.io.FileUtils;
import org.hibernate.Session;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.hnluchuan.core.support.Page;
import com.hnluchuan.staff.common.UserType;
import com.hnluchuan.staff.dto.RoleDTO;
import com.hnluchuan.staff.dto.UserDTO;
import com.hnluchuan.staff.model.Role;
import com.hnluchuan.staff.service.RoleService;
import com.hnluchuan.staff.service.UserRoleService;
import com.hnluchuan.staff.service.UserService;
import com.hnluchuan.staff.web.controller.BaseAdminController;

@Controller
@RequestMapping(value = "/admin/user", produces="text/html;charset=UTF-8")
public class AdminUserController extends BaseAdminController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RoleService roleService;



    @RequestMapping(value = "/detail")
    public String detail(Integer type, Long parentId, Map<String, Object> map, Long id, boolean seedUser) {
        if (id != null) {
            UserDTO dto = userService.load(id);
            map.put("n", dto);
        }
        map.put("seedUser", seedUser);
        map.put("provinces", provinceService.findAll());
        map.put("type", type);
        map.put("parentId", parentId);
        return "admin/user/user_detail";
    }

    @PreAuthorize("hasRole('user.add')")
    @ResponseBody
    @RequestMapping(value = "/save")
    public String save(UserDTO dto) throws Exception {
        if (dto.getId() == null) {
           /* List<UserDTO> user=userService.find(dto,null);
            if(user != null){
               throw  new  BizException("用户名已存在");
            }*/
            dto.setDeleted(false);
            dto.setType(UserType.Normal.getValue());
          //  dto.setPassword("123");

            Long id = userService.create(dto);
            userService.resetPassword("123", id);
        } else {
            dto.setDeleted(false);
            UserDTO old = userService.load(dto.getId());
            userService.updateAllFields(old);
        }
        return ok();
    }


    @RequestMapping(value = "/")
    public String delete(Long[] ids) throws IOException {
        userService.deleteByIds(ids);
        return ok();
    }

    @RequestMapping(value = "/list")
    public String list(Integer fromType, Integer type, UserDTO dto, Map<String, Object> map, Page page) {
        List<UserDTO> dtos = userService.find(dto, page);
        map.put("list", dtos);
        map.put("query", dto);
        map.put("type", type);
        map.put("fromType", fromType);
        return "admin/user/user_list";
    }

    @RequestMapping(value = "/auth")
    public String auth(Map<String, Object> map, Long userId, RoleDTO dto, Page page) {
        if (userId != null) {
            List<Role> roles = userRoleService.findRolesByUserId(userId);
            List<RoleDTO> list = roleService.list(dto, page);
            for (RoleDTO model : list) {
                for (Role role : roles) {
                    if (role.getId().longValue() == model.getId()) {
                        model.setChecked(true);
                    }
                }
            }
            map.put("userId", userId);
            map.put("list", list);
            map.put("query", dto);
        }
        return "admin/user/user_auth";
    }

    @RequestMapping(value = "/authSave")
    @ResponseBody
    public String authSave(Long[] ids, Long userId) {
        userRoleService.save(ids, userId);
        return ok();
    }

    @RequestMapping(value = "/reset")
    public String reset(Map<String, Object> map, Long userId) {
        UserDTO dto = userService.load(userId);
        map.put("n", dto);
        return "admin/user/user_reset";
    }

    /*@RequestMapping(value = "/idPicture")//身份证上传跳转界面
	public String IDload(HttpServletRequest request) throws Exception {
		return "admin/user/user_idPicture";
	}*/
    @RequestMapping(value = "/idPicture")//身份证上传跳转界面
    public String IDload(Map<String, Object> map) throws Exception {
        map.put("user", getCurrentUserDTO());//
        return "admin/user/user_idPicture";
    }


    @RequestMapping(value = "/editHeadImage")
    public String editHeadImage(Map<String, Object> map) {
        map.put("user", getCurrentUserDTO());
        return "admin/user/user_editHeadImage";
    }

	/*@RequestMapping(value = "/editHeadImage")
	public String fileLoad(Map<String, Object> map) {
		map.put("user", getCurrentUserDTO());
		return "admin/user/user_editHeadImage";
	}*/

    @RequestMapping("saveHeadImage")
    public String saveHeadImage(HttpServletRequest request) throws Exception {
        String file = saveFileAndReturnFileName(request, "file");//这个方法也可以获取前端forminput里面的内容
        UserDTO user = userService.load(getCurrentUserDTO().getId());
        if (StringUtils.isNotBlank(file)) {
            user.setHeadImage(file);
            userService.updateAllFields(user);
        }
        return successPage(null);
    }

    @RequestMapping("saveIdPicture")
    public String saveIdPicture(HttpServletRequest request) throws Exception {
        String file = saveFileAndReturnFileName(request, "file");
        UserDTO user = userService.load(getCurrentUserDTO().getId());
        if (StringUtils.isNotBlank(file)) {
            user.setIdPicture(file);
            userService.updateAllFields(user);
        }
        return successPage(null);
    }

    @ResponseBody
    @RequestMapping(value = "/resetPassword")
    public String resetPassword(String newPassword, Long userId) {
        userService.resetPassword(newPassword, userId);
        return ok();
    }

    @RequestMapping(value = "changePassword")
    public String changePassword(Map<String, Object> map) {
        UserDTO dto = getCurrentUserDTO();
        map.put("n", dto);
        return "admin/user/user_changePassword";
    }

    @RequestMapping(value = "saveChangePassword")
    public String saveChangePassword(String oldPassword, String newPassword, String confirmPassword, Long userId, Map<String, Object> map) {
        userService.changePassword(userId, oldPassword, newPassword, confirmPassword);
        return successPage(null);
    }

    @RequestMapping(value = "/search")
    public String search(UserDTO dto, Map<String, Object> map, Page page) {
        List<UserDTO> dtos = userService.find(dto, page);
        map.put("list", dtos);
        map.put("query", dto);
        return "admin/user/user_search";
    }

    @RequestMapping(value = "/uploadFile")
    public String uploadFile(Map<String, Object> map) {
        map.put("user", getCurrentUserDTO());
        return "admin/user/user_uploadFile";
    }

    @RequestMapping(value = "/downloadFile")
    public String daownloadFile(Map<String, Object> map) {
        map.put("user", getCurrentUserDTO());
        return "admin/user/user_downloadFile";
    }

    //上传文件会自动绑定到MultipartFile中,直接上傳到本地路徑中
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String upload(HttpServletRequest request, HttpSession session,
                         @RequestParam("description") String description,
                         @RequestParam("file") MultipartFile file) throws Exception {
        String filename = file.getOriginalFilename();
        String leftPath = session.getServletContext().getRealPath("/images");
        File uploadfile = new File(leftPath, filename);
        file.transferTo(uploadfile);
        String filePath =uploadfile.getAbsolutePath();//获得文件上传到本地的绝对路径
        UserDTO userDTO = getCurrentUserDTO();//

        userDTO.setText(filePath);
        userService.updateAllFields(userDTO);
         return successPage(null);

    }


    @RequestMapping(value = "/download")
    public ResponseEntity<byte[]> download(HttpServletRequest request
    ) throws Exception {
        //下载文件路径

        UserDTO userDTO = getCurrentUserDTO();
        String path = userDTO.getText();
        File file = new File(path);
        HttpHeaders headers = new HttpHeaders();
        //下载显示的文件名，解决中文名称乱码问题
        String downloadFielName = new String(file.getName().getBytes("UTF-8"), "iso-8859-1");
        //通知浏览器以attachment（下载方式）打开图片
        headers.setContentDispositionFormData("attachment", downloadFielName);
        //application/octet-stream ： 二进制流数据（最常见的文件下载）。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);
    }
    @RequestMapping(value = "/downloadEmployee")
    public ResponseEntity<byte[]> downloadEmployee(HttpServletRequest request,EmployeeDTO employeeDTO
    ) throws Exception {
        //下载文件路径

        String path = employeeDTO.getUser().getText();
        File file = new File(path);
        HttpHeaders headers = new HttpHeaders();
        //下载显示的文件名，解决中文名称乱码问题
        String downloadFielName = new String(file.getName().getBytes("UTF-8"), "iso-8859-1");
        //通知浏览器以attachment（下载方式）打开图片
        headers.setContentDispositionFormData("attachment", downloadFielName);
        //application/octet-stream ： 二进制流数据（最常见的文件下载）。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);
    }

    @RequestMapping(value = "/downloadPicture")
    public ResponseEntity<byte[]> downloadPicture(HttpServletRequest request
    ) throws Exception {
        //下载文件路径

        String path = (String) request.getSession().getAttribute("absolutePath");


        File file = new File(path);
        HttpHeaders headers = new HttpHeaders();
        //下载显示的文件名，解决中文名称乱码问题
        String downloadFielName = new String(file.getName().getBytes("UTF-8"), "iso-8859-1");
        //通知浏览器以attachment（下载方式）打开图片
        headers.setContentDispositionFormData("attachment", downloadFielName);
        //application/octet-stream ： 二进制流数据（最常见的文件下载）。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);
    }
}








